#ifndef PLCMODULE_H
#define PLCMODULE_H

#include <QObject>
#include "plcgraphicsscene.h"
#include "modbusmanager.h"

namespace Ui {
class MainWindow;
}

class PlcModule : public QObject
{
    Q_OBJECT
public:
    explicit PlcModule(Ui::MainWindow* ui, ModbusManager* modbusManager, QObject* parent = nullptr);
    void init();

    // 文件接口
    bool saveToFile(const QString& filePath);
    bool openFromFile(const QString& filePath);
    void resetDiagram();              // 新建/重置
    bool isModified() const { return m_isModified; }
    void setModified(bool m) { m_isModified = m; }

    // 从外部（例如主窗口）触发比较元件状态刷新，更新比较元件的 ON/OFF
    void applyDRegisterSnapshot(const QHash<int, quint16>& dregs);
    void updateRegisterDisplay(int address, quint16 value);

private slots:
    void prepareToCreateElement(PlcInstructionType type);
    void onElementCreated(PlcElement* item);
    void onCoilUpdated(int address, bool value);
    void onRegisterUpdated(int address, quint16 value);
    void onWriteCoilRequested(int address, bool value);

private:
    Ui::MainWindow* ui_;
    PlcGraphicsScene* m_scene;

    // 修改标记
    bool m_isModified = false;

    ModbusManager* modbusManager_;
    QHash<int, quint16> m_dRegisterSnapshot; // 存储D寄存器快照
};

#endif // PLCMODULE_H
